/**
 * Created by Administrator on 2017/6/20 0020.
 */
import {
    instance
} from '../../../src/Wap'
// 系统全局性变量
window.Wap = instance

$(function () {
    // 当前模块存储器
    var $storage = Wap.storage().table('wap_finance_account');
    // 数据帅选标识
    var filter = $storage.get('filter', 'all');
    var fltType = $storage.get('filter_type', 'part');  // 筛选类型
    var sCol = $storage.get('sCol', 'name');  // 高级搜索字段
    var superSearch = {};
    var $forward;

    // 数据列处理
    var curPage = 1,     // 当前列
        allPage,             // 总列数
        searchValue = ''
        ;
    var sTag = instance.amTag();
    sTag.def = 'name';

    /**
     * 获取查询值
     * @returns {null}
     */
    function getFilterWhere() {
        let vname = sTag.col;
        if(vname && superSearch){
            let data = {};
            data[vname] = searchValueByColb(searchValue);
            return data;
        }
        return null;
    }
    // 删除财务账单确定绑定事件
    function delCkeckEvt() {
        var dom = $(this);
        weui.confirm('您确定要删除此财务账单吗?', function(){
            var no = dom.parents('div.weui-media-box').data('no');
            Wap.ApiRequest('faccount/save',{mode:'D','no':no},function (rdata) {
                if(rdata.code == 1){
                    dom.parents('div.weui-panel__bd').remove();
                    weui.toast(rdata.msg);
                }
                else{
                    weui.alert(rdata.msg);
                }
            });
        });
    }
    /**
     * 数据渲染
     * @param {JSON} result
     * @returns {string}
     */
    function dataToList(result) {
        var xhtml = '';
        for(var i=0; i<result.length; i++){
            var v = result[i];
            xhtml += '<div class="weui-panel__bd">' +
                '<div class="weui-media-box weui-media-box_text" data-no="'+ Base64.encode(v.no)+'">' +
                    '<h4 class="weui-media-box__title">' +
                        '<i class="fa ' + (v.type == 'IN'? 'fa-plus-circle text-success':'fa-minus-circle text-info') + '"></i> '+
                            v.date+ '<span style="font-size: 0.78em;font-style: italic;">('+Wap.numberToZh(v.week,'dxq')+')</span> '+ 
                            '<a href="'+ Wap._wapurl + 'faccount/preview/item/' + v.no + '" title="详情">' +
                                '<span style="color:#CC6600;">' + v.money+ '</span>' + 
                                (v.name? ' <span style="color: #880000;font-size: 0.87em;font-style: italic;">' + v.name + '</span>':'') +
                            '</a>' + 
                    '</h4>' +
                    '<p class="weui-media-box__desc">'+ v.descrip + '</p>' +
                    '<ul class="weui-media-box__info">' +
                        '<li class="weui-media-box__info__meta"> '+ v.mtime + '</li>' +
                        '<li class="weui-media-box__info__meta">' +
                            '<a href="'+ Wap._wapurl + 'faccount/preview/item/' + v.no + '" style="color:#0E77CA;"><i class="fa fa-info"></i> 详情</a>' +
                        '</li>' +
                        '<li class="weui-media-box__info__meta">' +
                            '<a href="'+ Wap._wapurl + 'faccount/edit/item/' + v.no + '" style="color:#669966;"><i class="fa fa-pencil-square"></i> 编辑</a>' +
                        '</li>' +
                        '<li class="weui-media-box__info__meta">' +
                            '<a href="'+ Wap._wapurl + 'faccount/edit?tpl=' + v.no + '" style="color:#666666;"><i class="fa fa-plus-circle"></i> 模板新增</a>' +
                        '</li>' +
                        '<li class="weui-media-box__info__meta">' +
                            (v.detail_ctt ? '<a href="'+ Wap._wapurl + 'faccount/detail/item/' + v.no + '.html" style="color:#CCCC00;"><span class="weui-badge">' + v.detail_ctt + '</span>':'<a href="'+ Wap._wapurl + 'faccount/detail/item/' + v.no + '" style="color:#CCCCCC;"><i class="fa fa-plus-circle"></i>') +
                            '财务明细</a>' +
                        '</li>' +
                        '<li class="weui-media-box__info__meta">' +
                            '<a href="javascript:void(0);" class="js__item_del text-danger"><i class="fa fa-trash-o"></i> 删除</a>' +
                        '</li>' +
                        '' +
                    '</ul>' +
                '</div>' +
                '<div class="weui-flex aurora-border"></div>' +
                '</div>'
            ;
        }
        return xhtml;
    }
    /**
     * 数据渲染
     * @param {JSON} result
     * @returns {string}
     */
    function dataToListGroup(result){
        var xhtml = '';
        var vfilter = $storage.get('filter');
        for(var i=0; i<result.length; i++){
            var v = result[i];
            var tWeek = '';
            if(vfilter == 'day'){
                tWeek = '<span style="font-size: 0.78em;font-style: italic;">('+Wap.numberToZh(v.week,'dxq')+')</span> ';
            }
            var vbody = '<div class="weui-cell__bd">'+v.date +tWeek+ ' / <span class="text-success">'+v.money+'</span>￥</div>'
                + '<div class="weui-cell__ft"><span class="weui-badge">'+v.num+'</span></div>'
                ;
            var vheader = '';
            if(vfilter == 'month'|| vfilter == 'year'){
                xhtml += '<a class="weui-cell weui-cell_access" data-id="group_dvlist" href="'+
                    Wap.getWapUrl('freport/dynamic/'+vfilter+'/'+v.date, true)+'">'
                    + vbody
                    + '</a>'
                ;
            }
            else{
                xhtml += '<div class="weui-cell" data-id="group_dvlist">'
                    + vbody
                    + '</div>'
                ;
            }
        }
        if(xhtml){
            if($('[data-id="group_dvlist"]').length == 0){
                xhtml = '<div class="weui-cells">'+xhtml+'</div>';
            }
        }
        return xhtml;
    }
    /**
     * 获取财务账单
     * @param {number} page 
     * @param {string} groupType day,month,years
     * @returns 
     */
    function getSets(page, groupType) {
        groupType = groupType || $storage.get('filter', 'all');
        // groupType = groupType || 'all';
        // console.log(allPage,curPage);
        if(allPage && allPage < curPage){
            return weui.topTips('没有更多数据了！');
        }
        page = page? parseInt(page):1;
        var loading = instance.weuiLoading('数据加载中……');
        let financeSet = $('#finance_set');
        //@TODO 实现对 tag 的搜索
        Wap.ApiRequest('faccount/sets',{
            page:page, 
            group: groupType, 
            filter_type: $storage.get('filter_type', 'part'),
            ss: Wap.bsjson(superSearch),
            where: getFilterWhere(),
        },function (rdata) {
            loading.hide();
            if(rdata.code == 1){
                var data = rdata.data;
                var result = data.result;
                curPage = data.page;
                $('#sets_count').text(data.count);
                // 总列数计算
                if(!allPage) allPage = Wap.getAllPage(data.count,data.num);
                var xhtml = groupType == 'all'? dataToList(result): dataToListGroup(result);
                if('' != xhtml){
                    var xhtmlObj = $(xhtml);
                    xhtmlObj.find('.js__item_del').click(delCkeckEvt);
                    if(filter == groupType){
                        financeSet.append(xhtmlObj);
                    }else{
                        financeSet.html(xhtmlObj);
                    }
                    filter = groupType;
                }else{
                    if (financeSet.find('div').length > 0){
                        return weui.topTips('没有更多数据了！');
                    }
                    xhtml =
                        '<div class="weui-cells" style="min-height: 420px;">'
                        + '<a class="weui-cell weui-cell_access" href="'+ Wap._wapurl + 'faccount/edit'+ '">'
                        + '<div class="weui-cell__bd"><i class="fa fa-warning text-danger"></i></div>'
                        + '<div class="weui-cell__ft">'
                        + '您还没一条财务记录'
                        + '</div>'
                        + '</a>'
                        + '</div>';
                    financeSet.append(xhtml);
                }
            }else{
                weui.topTips(rdata.msg);
            }
        });
    }
    // 右滑动时返回
    Wap.SwipeRightBack();
    getSets();
    // (上拖)上滑动 - 数据翻页
    $('.weui-footer').swipeUp(function () {
       if(curPage < allPage){
           curPage = curPage + 1;
           getSets(curPage);
       }else{
           weui.topTips('没有更多数据！');
       }
    });
    // 更多数据加载
    $('#load_more_lnk').click(function () {
        if(curPage < allPage){
            curPage = curPage + 1;
            getSets(curPage);
        }else{
            weui.topTips('没有更多数据！');
            $(this).parents('div.weui-flex').hide();
        }
    });
    // 搜索字符串通配符
    var searchValueByColb = (v) => {
        let nRs = '=123456=';
        let v2 = v.replace(/\\\*/g, nRs);

        v2 = v2.replace(/\*/g, '%');
        v2 = v2.replace(new RegExp(nRs, 'g'), '*');
        return v2;
    };


    // 搜索框
    $('#search_lnk').click(function () {
        var dialog;
        let tags = sTag.getHtml({
            date: '日期',
            money: '金额',
            name: '名称',
            descrip: '描述',
            mtime: '维护时间',
            tag: '标签',
        });
        let content = `
            <div>
                ${tags}
                <div class="weui-cell">
                    <input type="text" class="weui-input" placeholder="请输入搜索值" value="${searchValue}">
                </div>
            </div>
        `;
        // 点击处理事件
        var clickEvtHandler = function(){
            var value = $('.search_dialog input.weui-input').val();
            if(value){
                searchValue = value;
                $('#finance_set').html('');
                getSets();
            }
            else{
                weui.topTips('搜索内容空！')
            }
        }
        dialog = weui.dialog({
            content: content,
            className: 'search_dialog',
            buttons: [{
                label: '关闭',
                type: 'default',
                onClick: function () {dialog.hide();}
            }, {
                label: '搜索',
                type: 'primary',
                onClick: clickEvtHandler
            }]
        });
        $('.search_dialog .weui-dialog').off('keydown').on('keydown', function(event){
            // console.log(event.keyCode)
            switch(event.keyCode){
                case 13:    // Enter
                    dialog.hide()
                    clickEvtHandler()
                    break;
                case 27:     // Esc , 移动版意义不大
                    dialog.hide()
                    break;
            }
        });
        sTag.useAmTag();
    });

    // 账单筛选
    $('#account_filter_lnk').click(function(){
        var cfilter = $storage.get('filter', 'all');
        var checkSquare = '<i class="fa fa-check-square-o"></i>';
        var square = '<i class="fa fa-square-o"></i>';        
        var menus = {
            all: {label:'全部', onClick:function(){$storage.update('filter', 'all');getSets();}},
            day: {label:'日汇总', onClick:function(){$storage.update('filter', 'day');getSets();}},
            month: {label:'月汇总', onClick:function(){$storage.update('filter', 'month');getSets();}},
            year: {label:'年汇总', onClick:function(){$storage.update('filter', 'year');getSets();}}
        };
        var menusopt = [];
        for(var k in menus){
            var el = menus[k];
            menusopt.push({
                label: (k == cfilter? checkSquare:square) + '  ' + el.label,
                onClick: el.onClick
            });
        }
        weui.actionSheet(menusopt);
    });

    // 滚动到监听
    $('#js__main').on('scroll', function(){
        var scrollTop = this.scrollTop;
        var $pageBar = $('#js__main').find('.page-bar');
        if($pageBar.length > 0){
            var pageBar = $pageBar[0];
            // console.log(pageBar.clientHeight, pageBar.offsetHeight, pageBar.offsetTop, this.scrollTop);
            if(pageBar.offsetTop < scrollTop){
                if(!$pageBar.hasClass('top-fixed')){
                    $pageBar.addClass('top-fixed');
                    // $('#js__main .js__title').html((Sumy.name || '日志系统')+' / '+ Page);
                }
                // $('#js__main .js__title').html(Page+' / '+ AllPage +' '+ (Sumy.name || '日志系统'));
                $forward.show();
            }else{
                if($pageBar.hasClass('top-fixed')){
                    $pageBar.removeClass('top-fixed');
                    $('#js__main .js__title').html('');
                }
                $forward.hide();
            }
        }
        // if(this.scrollHeight - scrollTop -50 <= this.clientHeight){
        //     if(Page >= AllPage){
        //         weui.toast('没有更多数据了');
        //         return false;
        //     }                    
        //     Page += 1;
        //     $instance.LoadLogList();
        // }
    });
    $forward = Wap.forwardTopScroll('#js__main');
    $forward.hide();

    /**
     * 设置tab控件
     * @class SettingTab
     */
    class SettingTab{
        constructor(instance){
            this.$instance = instance;
            this.DomListener();
            var sColer = $('[name="search_col"]')[0];
            sColer.value = sCol;

            //fltType
            $('#setting_group_'+fltType).attr('checked', true);
        }
        /**
         * 页面元素监听器
         * @memberof SettingTab
         */
        DomListener(){
            var $s = this;
            // 高级搜索选中值监听
            $('[name="search_col"]').change(function(){
                var el = $(this)[0];
                var value = el.value;
                $storage.update('sCol', value);
                sCol = value;
            });
            // 筛选类型
            $('[name="setting_group"]').change(function(){
                var el = $(this)[0];
                $storage.update('filter_type', el.value);
                if(filter != 'all'){
                    // 清除历史记录
                    $('#finance_set').html('');
                    getSets();
                    $s.$instance.open('js__main');
                }
            });
            // 高级搜索
            $('#super_search_lnk').click(function(){
                var value = $('[name="search_value"]')[0].value;
                var equal = $('[name="search_equal"]')[0].value;
                superSearch['super_search'] = {value, equal, sCol};
                //console.log(superSearch);
                // 清除历史记录
                $('#finance_set').html('');
                getSets();
                $s.$instance.open('js__main');
            });
        }
    }
    
    /**
     * tab 控件
     * @class Tab
     */
    class Tab{
        constructor(){
            var hash = location.hash;
            if(hash){
                this.open('js__'+hash.substr(1));
            }
            this.settingTab = new SettingTab(this);
        }
        // 打开指定的tab窗
        open(id){
            $('.weui-tab').css({'display':'none'});
            $('#'+ id).css({'display':null});
            location.hash = id.replace('js__', '');
        }
        // 设置tab窗
        settingTab(){}        
    }
    var $tab = new Tab();
    // 高级设置
    $('.tab__lnk').click(function(){
        var id = $(this).data('target');
        $tab.open(id);
    });
});